import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
// import router from '@/router/index'
import router from '../router';
import createPersistedState from 'vuex-persistedstate';


Vue.use(Vuex)

// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = require.context('./modules', true, /\.js$/)

// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
    // set './app.js' => 'app'
    const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
    const value = modulesFiles(modulePath)
    modules[moduleName] = value.default
    return modules
}, {})

// const loadView = (viewPath) => {
//     return () => import(`${viewPath}`)
// }

const loadView = (view) => {
    return (resolve) => require([`@/views${view}/index`], resolve)
}

const store = new Vuex.Store({
    state: {
        MenusList: [], // 用于存储菜单列表
        token: '',
        isLoadRouters: false

    },
    mutations: {
        SET_MENUS_LIST (state, menus) {
            state.MenusList = menus; // 更新菜单列表
        },

        ADD_ROUTE (state) {
            let routerList = JSON.parse(JSON.stringify(state.MenusList));
            routerList.forEach(item => {
                item.component = () => import('@/layout'); // 使用 import() 动态导入组件
                item.children.forEach(items => {
                    items.component = loadView(item.path)
                });
            });
            router.addRoutes(routerList);
        },
        SET_TOKEN: (state, token) => {
            state.token = token
            sessionStorage.setItem("token", token);
        },
        SET_ISLOADROUTERS: (state, isLoadRouters) => {
            state.isLoadRouters = isLoadRouters
        }
    },
    actions: {
        // 你可以在这里定义异步操作
        getlist ({ commit }, menus) {
            commit('SET_MENUS_LIST', menus); // 提交 mutation
        }
    },
    getters: {
        GET_TOKEN:state => {
          state.token = sessionStorage.getItem("token")
          return state.token
        },
        GET_ISLOADROUTERS:state=>{
          return state.isLoadRouters
        }
    },
    plugins: [createPersistedState({
        paths: ['MenusList'] // 只持久化 userName 和 company
    })],

    modules,
    getters
})

export default store
